package com.wqiuqiu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.wqiuqiu.common.R;
import com.wqiuqiu.common.to.SkuFullReductionTo;
import com.wqiuqiu.common.to.SkuLadderTo;
import com.wqiuqiu.common.to.SkuMemberPriceTo;
import com.wqiuqiu.common.to.SpuBoundTo;
import com.wqiuqiu.common.to.es.AttrModel;
import com.wqiuqiu.common.to.es.HasWareTo;
import com.wqiuqiu.common.to.es.SkuEsModel;
import com.wqiuqiu.gulimall.product.entity.*;
import com.wqiuqiu.gulimall.product.feign.CouponFeignService;
import com.wqiuqiu.gulimall.product.feign.SearchFeignService;
import com.wqiuqiu.gulimall.product.feign.WareFeignService;
import com.wqiuqiu.gulimall.product.service.*;
import com.wqiuqiu.gulimall.product.vo.*;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wqiuqiu.common.PageUtils;
import com.wqiuqiu.common.Query;

import com.wqiuqiu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    AttrService attrService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    SearchFeignService searchFeignService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;

    @Autowired

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        String catelogId = (String) params.get("catelogId");
        String brandId = (String) params.get("brandId");
        String status = (String) params.get("status");
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(brandId) && !brandId.equals("0")) {
            wrapper.eq("brand_id", brandId);
        }
        if (!StringUtils.isEmpty(catelogId) && !catelogId.equals("0")) {
            wrapper.eq("catalog_id", catelogId);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(obj -> obj.eq("id", key).or().like("spu_name", key));
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @GlobalTransactional
    @Transactional
    @Override
    public void saveSpuInfo(SpuinfoVo spuInfo) {
        //保存spu基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo, spuInfoEntity);
        Date date = new Date(System.currentTimeMillis());
        spuInfoEntity.setCreateTime(date);
        spuInfoEntity.setUpdateTime(date);
        this.save(spuInfoEntity);
        //保存Spu的描述图片
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        if (spuInfo.getDecript() != null && spuInfo.getDecript().size() > 0) {
            spuInfoDescEntity.setDecript(String.join(",", spuInfo.getDecript()));
            spuInfoDescService.save(spuInfoDescEntity);
        }
        //保存spu的图片集
        if (spuInfo.getImages() != null && spuInfo.getImages().size() > 0) {
            List<SpuImagesEntity> spuImagesEntities = spuInfo.getImages().stream().map(obj -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setImgName(spuInfo.getSpuName());
                spuImagesEntity.setImgUrl(obj);
                spuImagesEntity.setSpuId(spuInfoEntity.getId());
                return spuImagesEntity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(spuImagesEntities);
        }
        //保存spu的规格参数
        if (spuInfo.getBaseAttrs() != null && spuInfo.getBaseAttrs().size() > 0) {
            List<Long> attrIds = spuInfo.getBaseAttrs().stream().map(obj -> {
                return obj.getAttrId();
            }).collect(Collectors.toList());
            Collection<AttrEntity> attrEntities = attrService.listByIds(attrIds);
            List<ProductAttrValueEntity> productAttrValueEntities = attrEntities.stream().map(obj -> {
                ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
                attrValueEntity.setAttrName(obj.getAttrName());
                attrValueEntity.setSpuId(spuInfoEntity.getId());
                attrValueEntity.setAttrId(obj.getAttrId());
                attrValueEntity.setQuickShow(obj.getShowDesc());
                return attrValueEntity;
            }).collect(Collectors.toList());
            for (int i = 0; i < productAttrValueEntities.size(); i++) {
                productAttrValueEntities.get(i).setAttrValue(spuInfo.getBaseAttrs().get(i).getAttrValues());
            }
            productAttrValueService.saveBatch(productAttrValueEntities);
        }
        //保存当前spu对应的所有sku的信息
        //sku的基本信息
        List<Skus> skus = spuInfo.getSkus();
        if (skus != null && skus.size() > 0) {
            List<SkuInfoEntity> skuInfoEntities = skus.stream().map(obj -> {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                skuInfoEntity.setBrandId(spuInfo.getBrandId());
                skuInfoEntity.setCatalogId(spuInfo.getCatalogId());
                BeanUtils.copyProperties(obj, skuInfoEntity);
                skuInfoEntity.setSaleCount(0L);
//                skuInfoEntity.setSkuDesc();
                List<Images> images = obj.getImages();
                String defImage = "";
                for (Images image : images) {
                    if (image.getDefaultImg() == 1) {
                        defImage = image.getImgUrl();
                        break;
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defImage);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                return skuInfoEntity;
            }).collect(Collectors.toList());
            skuInfoService.saveBatch(skuInfoEntities);
            List<SkuImagesEntity> skuImagesEntities = new ArrayList<>();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = new ArrayList<>();
            List<SkuLadderTo> skuLadderTos = new ArrayList<>();
            List<SkuFullReductionTo> skuFullReductionTos = new ArrayList<>();
            List<SkuMemberPriceTo> skuMemberPriceTos = new ArrayList<>();
            for (int i = 0; i < skuInfoEntities.size(); i++) {
                SkuInfoEntity skuInfoEntity = skuInfoEntities.get(i);
                //保存sku的图片信息
                List<Images> images = skus.get(i).getImages();
                List<SkuImagesEntity> oneSkuImagesEntities = images.stream().map(obj -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    if (obj.getDefaultImg() == 1)
                        skuImagesEntity.setDefaultImg(1);
                    else
                        skuImagesEntity.setDefaultImg(0);
                    skuImagesEntity.setImgUrl(obj.getImgUrl());
                    return skuImagesEntity;
                }).filter(obj -> {
                    return !StringUtils.isEmpty(obj.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesEntities.addAll(oneSkuImagesEntities);
                //保存sku的销售属性信息
                List<Attr> attrs = skus.get(i).getAttr();
                List<SkuSaleAttrValueEntity> oneSkuSaleAttrValueEntities = attrs.stream().map(obj -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(obj, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueEntities.addAll(oneSkuSaleAttrValueEntities);
                //收集sku的优惠信息
                SkuLadderTo skuLadderTo = new SkuLadderTo();
                skuLadderTo.setSkuId(skuInfoEntity.getSkuId());
                BeanUtils.copyProperties(skus.get(i), skuLadderTo);
                skuLadderTo.setAddOther(skus.get(i).getCountStatus());
                //等于0表示没有优惠
                if (skuLadderTo.getFullCount() > 0) {
                    skuLadderTos.add(skuLadderTo);
                }
                //收集sku的满减信息
                SkuFullReductionTo skuFullReductionTo = new SkuFullReductionTo();
                BeanUtils.copyProperties(skus.get(i), skuFullReductionTo);
                skuFullReductionTo.setSkuId(skuInfoEntity.getSkuId());
                skuFullReductionTo.setAddOther(skus.get(i).getPriceStatus());
                //大于一件才打折
                if (skuFullReductionTo.getFullPrice().compareTo(new BigDecimal(0)) == 1) {
                    skuFullReductionTos.add(skuFullReductionTo);
                }
                //收集sku的会员折扣信息
                List<MemberPrice> memberPrice = skus.get(i).getMemberPrice();
                List<SkuMemberPriceTo> memberPriceTos = memberPrice.stream().map(obj -> {
                    SkuMemberPriceTo skuMemberPriceTo = new SkuMemberPriceTo();
                    skuMemberPriceTo.setSkuId(skuInfoEntity.getSkuId());
                    skuMemberPriceTo.setMemberLevelId(obj.getId());
                    skuMemberPriceTo.setMemberLevelName(obj.getName());
                    skuMemberPriceTo.setMemberPrice(obj.getPrice());
                    skuMemberPriceTo.setAddOther(1);
                    return skuMemberPriceTo;
                }).filter(obj -> {
                    return obj.getMemberPrice().compareTo(new BigDecimal(0)) == 1;
                }).collect(Collectors.toList());
                skuMemberPriceTos.addAll(memberPriceTos);


            }
            skuImagesService.saveBatch(skuImagesEntities);
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
            //保存优惠、满减信息，需要调用远程服务
            //保存spu的积分信息
            Bounds bounds = spuInfo.getBounds();
            SpuBoundTo spuBoundTo = new SpuBoundTo();
            BeanUtils.copyProperties(bounds, spuBoundTo);
            spuBoundTo.setSpuId(spuInfoEntity.getId());
            R r = couponFeignService.saveBound(spuBoundTo);
            if (r.getCode() != 0) {
                log.error("保存失败!!!");
            }
            //保存sku的优惠信息
            R r1 = couponFeignService.saveLadder(skuLadderTos);
            if (r1.getCode() != 0) {
                log.error("保存失败!!!");
            }

            //保存sku的满减信息
            couponFeignService.saveFullReduction(skuFullReductionTos);
            //保存sku的会员信息
            couponFeignService.saveMemberPrice(skuMemberPriceTos);


        }


    }

    @Transactional
    @Override
    public void spuUp(Long spuId) {
        //修改spu的状态->上架
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        spuInfoEntity.setId(spuId);
        List<AttrModel> attrModels2 = null;
        //sku的可检索属性（销售属性排外，规格属性中可以被检索的属性）
        List<ProductAttrValueEntity> productAttrValueEntities = attrService.getSpuAttrInfoBySpuId(spuId);
        if (productAttrValueEntities.size() > 0) {
            List<Long> ids = productAttrValueEntities.stream().map(attr -> {
                return attr.getAttrId();
            }).collect(Collectors.toList());
            //规格属性中可以被检索的属性
            ids = attrService.getSearchAttrs(ids);
            Set<Long> idsSet = new HashSet<>(ids);
            attrModels2 = productAttrValueEntities.stream().filter(obj -> {
                return idsSet.contains(obj.getAttrId());
            }).map(obj -> {
                AttrModel attrModel = new AttrModel();
                BeanUtils.copyProperties(obj, attrModel);
                return attrModel;
            }).collect(Collectors.toList());
        }

        //将要存储在es中数据分装好，发给es。
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //查找是否有库存，发一次请求，查询全部的sku是否有库存
        //TODO 有错误 wareSku = null
        Map<Long, Long> wareSku = null;
        try {
            R info = wareFeignService.getWarebySkuIds(skuIds);
            TypeReference<List<HasWareTo>> typeReference = new TypeReference<List<HasWareTo>>() {
            };
            wareSku = info.getData(typeReference).stream()
                    .collect(Collectors.toMap(HasWareTo::getSkuId, HasWareTo::getStock));
            if (info.getCode() != 0) {
                log.error("仓储服务远程调用失败！！！");
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e.getClass());
        }

        List<AttrModel> finalAttrModels = attrModels2;
        Map<Long, Long> finalWareSku = wareSku;
        List<SkuEsModel> skuEsModels = skuInfoEntities.stream().map(obj -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(obj, skuEsModel);
            skuEsModel.setSkuImg(obj.getSkuDefaultImg());
            skuEsModel.setSkuPrice(obj.getPrice());
            skuEsModel.setSpuId(spuId);
            //库存
            if (finalWareSku == null) {
                //库存服务没查出来
                skuEsModel.setHasStock(true);
            } else {
                if (finalWareSku.get(obj.getSkuId()) > 0) {
                    skuEsModel.setHasStock(true);
                } else {
                    skuEsModel.setHasStock(false);
                }
            }

            //品牌图片，名称
            BrandEntity info = brandService.getById(skuEsModel.getBrandId());
            String logo = info.getLogo();
            String name = info.getName();
            skuEsModel.setBrandImg(logo);
            skuEsModel.setBrandName(name);
            // TODO 商品热力值
            skuEsModel.setHotScore(0L);
            //分类名称
            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            skuEsModel.setAttrs(finalAttrModels);

            return skuEsModel;
        }).collect(Collectors.toList());
        //发送给es保存
        R r = searchFeignService.productUp(skuEsModels);
        if (r.getCode() == 0){
            //最后当es返回成功之后在修改上架状态
            spuInfoEntity.setPublishStatus(1);
            spuInfoEntity.setUpdateTime(new Date());
            this.updateById(spuInfoEntity);
        }
    }

    @Override
    public SpuInfoEntity getSpuinfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        SpuInfoEntity spuInfoEntity = this.getById(skuInfoEntity.getSpuId());
        return spuInfoEntity;
    }


}